using System;
using System.Data;
using System.Windows.Forms;
namespace mywine.Class
{
    ///<summary>
    ///Date init:  
    ///Date modify:
    ///By:
    ///
    ///</summary>
    public class CType : TUnit.Class.Class
    {
        #region Declares
        int _typeid = -1;
        string _Typename = "";
        int _storeid = -1;
        #endregion

        #region Constructors
        public CType()
        {
        }
        public CType(TUnit.Class.CLogin Login)
        {
            base.Login = Login;
        }
        public CType(TUnit.Class.CLogin Login, object ObjId)
        {
            base.Login = Login;
            using (AccDBType db = new AccDBType())
            {
                this.Populate((CType)db.GetClass(Login, ObjId));
            }
        }
        public CType(TUnit.Class.CLogin Login, TUnit.Data.IProvider p, System.Data.DataRow dr)
        {
            base.Login = Login;
            this.Populate(p, dr);
        }
        public CType(TUnit.Class.CLogin Login, TUnit.Data.IProvider p, object ObjId)
        {
            base.Login = Login;
            using (AccDBType db = new AccDBType())
            {
                this.Populate((CType)db.GetClass(Login, p, ObjId));
            }
        }
        #endregion

        #region Methods
        public void Populate(TUnit.Data.IProvider p, DataRow dr)
        {
            if (dr != null)
            {
                try
                {
                    if (dr.Table.Columns.IndexOf("typeid") >= 0)
                    {
                        this._typeid = (dr["typeid"] != DBNull.Value ? Convert.ToInt32(dr["typeid"]) : -1);
                    }
                    //else
                    //{//Tao Field neu bang CSDL chua ton tai Field nay
                    //	p.ExecuteNonQuery("ALTER TABLE tbl_Types ADD typeid [int] NULL");
                    //}
                    if (dr.Table.Columns.IndexOf("Typename") >= 0)
                    {
                        this._Typename = (dr["Typename"] != DBNull.Value ? Convert.ToString(dr["Typename"]) : "");
                    }
                    //else
                    //{//Tao Field neu bang CSDL chua ton tai Field nay
                    //	p.ExecuteNonQuery("ALTER TABLE tbl_Types ADD Typename [nvarchar] (50) NULL");
                    //}
                    if (dr.Table.Columns.IndexOf("storeid") >= 0)
                    {
                        this._storeid = (dr["storeid"] != DBNull.Value ? Convert.ToInt32(dr["storeid"]) : -1);
                    }
                    //else
                    //{//Tao Field neu bang CSDL chua ton tai Field nay
                    //	p.ExecuteNonQuery("ALTER TABLE tbl_Types ADD storeid [int] NULL");
                    //}
                }
                catch { }
            }
        }
        public void Populate(CType Obj)
        {
            if (Obj != null)
            {
                try
                {
                    this._typeid = Obj.typeid;
                    this._Typename = Obj.Typename;
                    this._storeid = Obj.storeid;
                }
                catch { }
            }
        }
        public override bool Save()
        {
            using (TUnit.Data.IProvider p = new TUnit.Data.OleDb(Login.Connectionstring))
            {
                if (p.Open())
                {
                    p.OpenTransaction();
                    using (AccDBType db = new AccDBType())
                    {
                        if (this.EventSaving != null)
                            this.EventSaving(this);
                        if (db.Save(p, this))
                        {
                            p.CloseTransaction();
                            p.Close();
                            if (this.EventSaved != null)
                                this.EventSaved(this);
                            return true;
                        }
                        else
                        {
                            p.Rollback();
                            p.CloseTransaction();
                            p.Close();
                            if (this.EventSaveError != null)
                                this.EventSaveError(this);
                            return false;
                        }
                    }
                }
            }
            return false;
        }
        public override bool Save(TUnit.Data.IProvider p)
        {
            using (AccDBType db = new AccDBType())
            {
                if (db.Save(p, this))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        public override bool Delete()
        {
            using (TUnit.Data.IProvider p = new TUnit.Data.OleDb(Login.Connectionstring))
            {
                if (p.Open())
                {
                    p.OpenTransaction();
                    using (AccDBType db = new AccDBType())
                    {
                        if (this.EventDeleting != null)
                            this.EventDeleting(this);
                        if (db.Delete(p, this))
                        {
                            p.CloseTransaction();
                            p.Close();
                            if (this.EventDeleted != null)
                                this.EventDeleted(this);
                            return true;
                        }
                        else
                        {
                            p.Rollback();
                            p.CloseTransaction();
                            p.Close();
                            if (this.EventDeleteError != null)
                                this.EventDeleteError(this);
                            return false;
                        }
                    }
                }
            }
            return false;
        }
        public override bool Delete(TUnit.Data.IProvider p)
        {
            using (AccDBType db = new AccDBType())
            {
                if (db.Delete(p, this))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public string toString()
        {
            return
                this.typeid.ToString() + "|"
                + this.Typename + "";
        }

        public static string toString(TUnit.Class.CCollection Collection)
        {
            string str = "";
            if (Collection != null)
            {
                for (int i = 0; i < Collection.Count; i++)
                {
                    CType o = (CType)Collection[i];
                    str += o.toString();
                    if (i != (Collection.Count -1))
                        str += "@TYPE";
                }
            }
            return str;
        }
        #endregion

        #region Events
        public delegate void OnEventSaveError(CType obj);
        public event OnEventSaveError EventSaveError;
        public delegate void OnEventSaving(CType Type);
        public event OnEventSaving EventSaving;
        public delegate void OnEventSaved(CType Type);
        public event OnEventSaved EventSaved;
        public delegate void OnEventDeleting(CType Type);
        public event OnEventSaving EventDeleting;
        public delegate void OnEventDeleted(CType Type);
        public event OnEventDeleted EventDeleted;
        public delegate void OnEventDeleteError(CType obj);
        public event OnEventDeleteError EventDeleteError;
        #endregion

        #region Properties
        public int typeid
        {
            get { return this._typeid; }
            set
            {
                if (this._typeid != value)
                {
                    this._typeid = value;
                }
            }
        }
        public string Typename
        {
            get { return this._Typename; }
            set
            {
                if (this._Typename != value)
                {
                    this._Typename = value;
                }
            }
        }
        public int storeid
        {
            get { return this._storeid; }
            set
            {
                if (this._storeid != value)
                {
                    this._storeid = value;
                }
            }
        }

        System.Drawing.Bitmap _icon = null;
        /// <summary>
        /// 
        /// </summary>
        public System.Drawing.Bitmap Icon
        {
            get
            {
                if (_icon == null)
                {
                    _icon = new System.Drawing.Bitmap(Application.StartupPath + "\\Icons\\check3.png");
                }
                return _icon;
            }
            set { _icon = value; }
        }

        bool _Checked = true;

        public bool Checked
        {
            get { return _Checked; }
            set 
            {
                if (_Checked != value || _icon == null)
                {
                    if(value)
                        _icon = new System.Drawing.Bitmap(Application.StartupPath + "\\Icons\\Checked.png");
                    else
                        _icon = new System.Drawing.Bitmap(Application.StartupPath + "\\Icons\\unChecked.png");

                    _Checked = value;
                }
            }
        }

        public TUnit.Class.CCollection _Collection = null;
        public TUnit.Class.CCollection Collection
        {
            get
            {
                if (this._Collection == null)
                {
                    using (AccDBWine db = new AccDBWine())
                    {
                        TUnit.Class.CCollection MyCollection = new TUnit.Class.CCollection();
                        db.GetCollection(this, MyCollection);
                        this._Collection = MyCollection;
                    }
                }
                return this._Collection;
            }
        }
        #endregion
    }

    #region Class AccDB
    public class AccDBType : TUnit.Class.AccDB
    {
        /// <summary>
        /// 
        /// </summary>
        public AccDBType()
        {
        }
        /// <summary>
        ///Phuong thuc dung dien du lieu len Combo 
        /// </summary>
        /// <param name="Login"></param>
        /// <param name="cmb"></param>
        /// <param name="extName"></param>
        public override void FillComboBox(TUnit.Class.CLogin Login, ComboBox cmb, string extName)
        {
            TUnit.Data.IProvider p = new TUnit.Data.OleDb(Login.Connectionstring);
            if (p.Open())
            {
                string sql = "SELECT typeid, TypeName";
                sql += " FROM  tbl_Types";
                sql += " WHERE (typeid >= 0)";
                sql += " ORDER BY TypeName";
                DataTable table = p.OpenTable(sql, "tbl_Types");
                if (table != null)
                {
                    if (extName != "")
                    {
                        System.Data.DataRow row = table.NewRow();
                        row["TypeName"] = extName;
                        row["typeid"] = "-1";
                        table.Rows.Add(row);
                    }
                    cmb.DataSource = table;
                    cmb.DisplayMember = "TypeName";
                    cmb.ValueMember = "typeid";
                    p.Close();
                }
            }
        }
        /// <summary>
        ///Doc doi tuong tu CSDL theo ID chi dinh
        /// </summary>
        /// <param name="p"></param>
        /// <param name="ObjId"></param>
        /// <returns></returns>
        public override TUnit.Class.Class GetClass(TUnit.Class.CLogin Login, TUnit.Data.IProvider p, object ObjId)
        {
            try
            {
                string sql = "SELECT * FROM tbl_Types WHERE (typeid = " + ObjId + ")";
                DataTable table = p.OpenTable(sql, "tbl_Types");
                if ((table != null) && (table.Rows.Count > 0))
                {
                    return new CType(Login, p, table.Rows[0]);
                }
            }
            catch
            {
            }
            return null;
        }
        /// <summary>
        /// Luu doi tuong vao CSDL
        /// </summary>
        /// <param name="p"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Save(TUnit.Data.IProvider p, TUnit.Class.Class obj)
        {
            CType Type = (CType)obj;
            string sql = "SELECT * FROM tbl_Types";
            sql += " WHERE typeid =" + Type.typeid + "";
            //sql +=" AND CompanyId =" + Type.CompanyId + "";
            DataTable dt = p.OpenTable(sql, "tbl_Types");
            if (dt != null)
            {
                DataRow row = null;
                if (dt.Rows.Count == 1 && Type.typeid != -1)
                {
                    row = dt.Rows[0];
                }
                else
                {
                    Type.typeid = Convert.ToInt32(p.InitIDKey("typeid", "tbl_Types", null));
                    row = dt.NewRow();
                    dt.Rows.Add(row);
                }
                row["typeid"] = Type.typeid;
                row["Typename"] = Type.Typename;
                row["storeid"] = Type.storeid;
                if (!p.UpdateTable("tbl_Types", dt))
                {
                    return false;
                }
                //if(Type._Type<Name>Collection != null)
                //{
                //	if (!Type.Type<Name>Collection.Save(p))
                //	{
                //		return false;
                //	}
                //}
                return true;
            }
            return false;
        }
        /// <summary>
        ///Xoa doi tuong khoi CSDL 
        /// </summary>
        /// <param name="p"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Delete(TUnit.Data.IProvider p, TUnit.Class.Class obj)
        {
            CType Type = (CType)obj;
            string sql = "DELETE FROM tbl_Types";
            sql += " WHERE typeid =" + Type.typeid + "";
            //sql +=" AND CompanyId =" + Type.CompanyId + "";
            return p.ExecuteNonQuery(sql);
        }
        /// <summary>
        /// Lay ve danh sach cac doi tuong tren CSDL
        /// </summary>
        /// <param name="p"></param>
        /// <param name="Collection"></param>
        public override void GetCollection(TUnit.Class.CLogin Login, TUnit.Data.IProvider p, TUnit.Class.CCollection Collection)
        {
            string sql = "SELECT * FROM tbl_Types ORDER BY TypeName";
            DataTable table = p.OpenTable(sql, "tbl_Types");
            if (table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    CType o = new CType(Login, p, row);
                    Collection.Add(o);
                }
            }
        }
        /// <summary>
        /// Lay ve danh sach cac doi tuong con cua doi obj neu co (danh cho loai du lieu quan he 2 bang cha con)
        /// </summary>
        /// <param name="Login"></param>
        /// <param name="Collection"></param>
        public override void GetCollection(TUnit.Data.IProvider p, TUnit.Class.Class obj, TUnit.Class.CCollection Collection)
        {
            if (obj is CStore)
            {
                string sql = "SELECT * FROM tbl_Types WHERE storeid ={0}";
                sql = String.Format(sql, ((CStore)obj).storeid);
                DataTable table = p.OpenTable(sql, "tbl_Types");
                if (table != null)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        CType o = new CType(obj.Login, p, row);
                        Collection.Add(o);
                    }
                }
            }
            if (obj is CWineColor)
            {
                string sql = "SELECT * FROM tbl_Types WHERE winecolorid ={0}";
                sql = String.Format(sql, ((CWineColor)obj).winecolorid);
                DataTable table = p.OpenTable(sql, "tbl_Types");
                if (table != null)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        CType o = new CType(obj.Login, p, row);
                        Collection.Add(o);
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Login"></param>
        /// <param name="Collection"></param>
        /// <param name="storeid"></param>
        /// <param name="style"></param>
        public void GetCollection(TUnit.Class.CLogin Login, TUnit.Class.CCollection Collection, int storeid, string style)
        {
            TUnit.Data.IProvider p = new TUnit.Data.OleDb(Login.Connectionstring);
            if (p.Open())
            {
                //string sql = "SELECT * FROM tbl_Types WHERE storeid ={0} AND style='{1}'";
                string sql = "SELECT DISTINCT tbl_types.typeid, tbl_types.typename, tbl_wines.style";
                sql += " FROM tbl_types INNER JOIN";
                sql += " tbl_wines ON tbl_types.typeid = tbl_wines.locaid";
                sql += " WHERE(tbl_wines.storeid = {0}) AND (tbl_wines.style = N'{1}')";
                sql = String.Format(sql, storeid, style);
                DataTable table = p.OpenTable(sql, "tbl_Types");
                if (table != null)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        CType o = new CType(Login, p, row);
                        Collection.Add(o);
                    }
                }
            }
        }
    }
    #endregion
}
